﻿using System.Net;
using Infrastructure.Configuration;


namespace WebApi.Middleware;

public class IpWhitelistMiddleware(RequestDelegate next, IConfiguration configuration)
{
    public async Task InvokeAsync(HttpContext context)
    {
        IPAddress? remoteIp = context.Connection.RemoteIpAddress;
        string[] allowedIPs = configuration.GetSectionOrThrow<string[]>("SafeIpList");

        if (remoteIp != null &&
            !IPAddress.IsLoopback(remoteIp) && 
            !allowedIPs.Contains(remoteIp.ToString()))
        {
            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            await context.Response.WriteAsync("Access denied for IP: " + remoteIp);
            return;
        }

        await next(context);
    }
}
